{{define "cp_serverstats"}}

{{template "cp_head" .}}

<link rel="stylesheet" href="/static/vendorr/morris/morris.css" />
<link rel="stylesheet" href="/static/vendorr/chartist/chartist.min.css" />

<header class="page-header">
    <h2>Server stats - {{.ActiveGuild.Name}} {{if .Public}}<a href="/"><small>by YAGPDB.xyz</a>{{end}}</small></h2>
</header>

{{template "cp_alerts" .}}


<div class="row">
    <div class="col-lg-12">
        {{if (not .Config.Public | and .Public) }}
        <h1>Public access has been disabled by the server admins.</h1>
        {{end}}
        {{if not .Public}}
        <button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#stats-settings-collapse"
            aria-expanded="false" aria-controls="stats-settings-collapse">
            Stats Settings
        </button>
        <a class="btn btn-primary {{if not .Config.Public}}disabled{{end}}" {{if .Config.Public}}
            href="/public/{{.ActiveGuild.ID}}/stats" {{end}}>Public link (only works if stats are set to public)</a>
        <div class="collapse" id="stats-settings-collapse">
            <section class="card">
                <div class="card-body">
                    <form method="post" action="/manage/{{.ActiveGuild.ID}}/stats/settings" data-async-form>

                        {{checkbox "Public" "stats-public-check" `Make server stats publicly accessible` .Config.Public}}

                        <label>Ignore channels</label>
                        <div class="form-group mb-4">
                            <select data-plugin-multiselect class="form-control populate" name="IgnoreChannels"
                                id="IgnoreChannels" multiple="multiple">
                                {{textChannelOptionsMulti .ActiveGuild.Channels .Config.ParsedChannels}}
                            </select>
                        </div>
                        <button type="submit" class="btn btn-success btn-sm">Save</button>
                    </form>
                </div>
            </section>
        </div>
        {{end}}
    </div>
    <!-- /.col-lg-12 -->
</div>

<div class="row">
    <!-- Stats widgets -->
    {{mTemplate "serverstats_stats_widget" "Icon" "comments" "BG" "primary" "Content" "New messages so far today" "ValueID" "messages-24h"}}
    {{mTemplate "serverstats_stats_widget" "Icon" "user-plus" "BG" "success" "Content" "Members joined/left so far today" "ValueID" "members-changed-24h"}}
    {{mTemplate "serverstats_stats_widget" "Icon" "user" "BG" "tertiary" "Content" "Online members" "ValueID" "online-members"}}
    {{mTemplate "serverstats_stats_widget" "Icon" "users" "BG" "quaternary" "Content" "Total members" "ValueID" "total-members"}}
</div>
<div class="row">
    <!-- Graph -->
    <div class="col-12">
        <section class="card bg-default">
            <header class="card-header">
                <h2 class="card-title">Channels last 24 hours</h2>
            </header>

            <div class="card-body">
                <div id="channels-chart-24h"></div>
            </div>
        </section>
    </div>
</div>

<div class="row">
    <div class="col">
        <h2>Charts<small><span id="serverstats-status"> Loading...</span></small></h2>
    </div>
    <div class="col">
        <!-- <div class="form-group"> -->
        <select id="timespan-dropdown" class="form-control" onchange="timespanDropdownChanged()">
            <option value="2"> Past 2 days (testing)</option>
            <option value="7" {{if not .IsGuildPremium}} selected{{end}}> Past 7 days</option>
            <option value="30" {{if .IsGuildPremium}} selected {{else}} disabled {{end}}> Past 30 days
                {{if not .IsGuildPremium}}(premium only){{end}}</option>
            <option value="365" {{if not .IsGuildPremium}} disabled{{end}}> Past 365 days
                {{if not .IsGuildPremium}}(premium only){{end}}</option>
            <option value="-1" {{if not .IsGuildPremium}} disabled{{end}}> All time {{if not .IsGuildPremium}}(premium
                only){{end}}</option>
        </select>
        <!-- </div> -->
    </div>
</div>

<div class="row">
    <!-- Graph -->
    <div class="col-lg-6">
        <section class="card bg-default">
            <header class="card-header">
                <h2 class="card-title">Joins / Leaves</h2>
            </header>

            <div class="card-body">
                <div id="chart-joins-leaves"></div>
            </div>
        </section>
    </div>

    <!-- Graph -->
    <div class="col-lg-6">
        <section class="card bg-default">
            <header class="card-header">
                <h2 class="card-title">Total Members</h2>
            </header>

            <div class="card-body">
                <div id="chart-total-members"></div>
            </div>
        </section>
    </div>
</div>

<div class="row">
    <!-- Graph -->
    <div class="col-12">
        <section class="card bg-default">
            <header class="card-header">
                <h2 class="card-title">Number of messages (excl. Bots)</h2>
            </header>

            <div class="card-body">
                <div id="chart-message-counts"></div>
            </div>
        </section>
    </div>
</div>

<!-- /.row -->
<script type="text/javascript">
    // cause of the async partial loader, we need to manually clear the interval when we navigate
    var firstStatsView;
    var statsInterval;
    if (!firstStatsView) {
        firstStatsView = true;
        window.addEventListener("customnavigate", function (e) {
            console.log("cleared interval");
            window.clearInterval(statsInterval);
        })
    }

    var fetchCharts = null;
    $(function () {
        var channelMessagesBarChart = null;
        function dailyStatsCB() {
            try {
                var parsedStats = JSON.parse(this.responseText);
            } catch (e) {
                return
            }

            var channelMessages = parsedStats.channels_messages

            var chartData = [];
            var total = 0;
            for (var key in channelMessages) {
                total += channelMessages[key].count;
                chartData.push({
                    x: channelMessages[key].name,
                    y: channelMessages[key].count,
                })
            }
            if (channelMessagesBarChart) {
                channelMessagesBarChart.setData(chartData);
            } else {
                channelMessagesBarChart = Morris.Bar({
                    element: 'channels-chart-24h',
                    data: chartData,
                    xkey: 'x',
                    ykeys: ['y'],
                    labels: ['Messages'],
                    hideHover: 'auto',
                    resize: true
                });
            }

            $("#messages-24h").text(total);
            $("#members-changed-24h").text("+" + parsedStats.joined_day + " -" + parsedStats.left_day);
            $("#total-members").text(parsedStats.total_members_now)
            $("#online-members").text(parsedStats.online_now)
        }

        function fetchDailyStats() {
            console.log("Fetching stats...");
            createRequest("GET", "/{{if .Public}}public{{else}}manage{{end}}/{{.ActiveGuild.ID}}/stats/daily_json", null, dailyStatsCB);
        }
        statsInterval = setInterval(fetchDailyStats, 10000);
        fetchDailyStats(); // Fetch the initial stats

        var joinsLeavesChart = null;
        var totalMembersChart = null;
        var messagesChart = null;
        function chartStatsCB() {
            try {
                var parsedStats = JSON.parse(this.responseText);
            } catch (e) {
                return
            }

            var stats = parsedStats.data
            // var memberStats = parsedStats.member_chart_data

            if (joinsLeavesChart) {
                joinsLeavesChart.setData(stats);
            } else {
                joinsLeavesChart = Morris.Area({
                    element: 'chart-joins-leaves',
                    data: stats,
                    xkey: 't',
                    ykeys: ['joins', 'leaves'],
                    labels: ['Joins', 'Leaves'],
                    hideHover: 'auto',
                    resize: true,
                    dateFormat: chartDateFormatter,
                    behaveLikeLine: true,
                    pointSize: 1,
                });
            }

            if (totalMembersChart) {
                totalMembersChart.setData(stats);
            } else {
                totalMembersChart = Morris.Area({
                    element: 'chart-total-members',
                    data: stats,
                    xkey: 't',
                    ykeys: ['num_members', 'max_online'],
                    labels: ['Total members', 'Online members'],
                    hideHover: 'auto',
                    resize: true,
                    dateFormat: chartDateFormatter,
                    behaveLikeLine: true,
                    pointSize: 1,
                });
            }

            if (messagesChart) {
                messagesChart.setData(stats);
            } else {
                messagesChart = Morris.Area({
                    element: 'chart-message-counts',
                    data: stats,
                    xkey: 't',
                    ykeys: ['num_messages'],
                    labels: ['Messages'],
                    hideHover: 'auto',
                    resize: true,
                    dateFormat: chartDateFormatter,
                    pointSize: 1,
                });
            }

            var nDays = parsedStats.days
            if (nDays <= 0) {
                nDays = "infinite"
            }
            $("#serverstats-status").text(" over the last  " + nDays + " days")
        }

        fetchCharts = function (days) {
            $("#serverstats-status").text("  Loading...")
            createRequest("GET", "/{{if .Public}}public{{else}}manage{{end}}/{{.ActiveGuild.ID}}/stats/charts?days=" + days, null, chartStatsCB);
        }
        fetchCharts(30);
    })


    function chartDateFormatter(t) {
        const options = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };
        return new Date(t).toLocaleDateString(options);
    }

    function timespanDropdownChanged() {
        var dropdown = document.getElementById("timespan-dropdown");
        fetchCharts(dropdown.value)
    }
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<!-- /#wrapper -->
<style>
    .stats-widget {
        min-width: 250px !important;
        word-break: normal !important;
    }

    .stats-widget h4 {
        word-break: normal !important;
    }
</style>
{{template "cp_footer" .}}
{{end}}

{{define "serverstats_stats_widget"}}
<div class="col-3 stats-widget">
    <section class="card">
        <div class="card-body bg-{{.BG}}">
            <div class="widget-summary">
                <div class="widget-summary-col widget-summary-col-icon">
                    <div class="summary-icon">
                        <i class="fa fa-{{.Icon}}"></i>
                    </div>
                </div>
                <div class="widget-summary-col">
                    <div class="summary">
                        <h4 class="title">{{.Content}}</h4>
                        <div class="info">
                            <strong class="amount" id="{{.ValueID}}">Loading...</strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>
{{end}}